<template>
	<view class="edit-parts-container">
		<!-- 图片上传 -->
		<view class="upload-section">
			<u-upload
				:fileList="fileList"
				@afterRead="afterRead"
				@delete="deletePic"
				name="partsImage"
				multiple
				:maxCount="1"
				width="120rpx"
				height="120rpx"
			>
				<view class="upload-placeholder" hover-class="upload-placeholder-hover">
					<u-icon name="plus" color="#fff" size="24"></u-icon>
					<text>{{ fileList.length ? '更换图片' : '添加图片' }}</text>
				</view>
			</u-upload>
		</view>
		
		<!-- 基本信息 -->
		<view class="form-item">
			<text class="form-label required">配件名称</text>
			<u--input
				class="form-input"
				placeholder="请输入配件名称"
				placeholderStyle="color: #c0c4cc;"
				border="none"
				v-model="formData.name"
				fontSize="28rpx"
			></u--input>
		</view>
		
		<view class="form-item">
			<text class="form-label">型号</text>
			<u--input
				class="form-input"
				placeholder="请输入型号"
				placeholderStyle="color: #c0c4cc;"
				border="none"
				v-model="formData.model"
				fontSize="28rpx"
			></u--input>
		</view>
		
		<view class="form-item">
			<text class="form-label">适用范围</text>
			<u--input
				class="form-input"
				placeholder="请输入适用范围"
				placeholderStyle="color: #c0c4cc;"
				border="none"
				v-model="formData.applicable"
				fontSize="28rpx"
			></u--input>
		</view>
		
		<view class="form-item">
			<text class="form-label">当前库存</text>
			<u--input
				class="form-input"
				placeholder="0"
				type="number"
				placeholderStyle="color: #c0c4cc; text-align: right;"
				border="none"
				v-model="formData.stock"
				fontSize="28rpx"
				inputAlign="right"
			></u--input>
		</view>
		
		<view class="form-item">
			<text class="form-label">价格</text>
			<u--input
				class="form-input"
				placeholder="0.00"
				type="number"
				placeholderStyle="color: #c0c4cc; text-align: right;"
				border="none"
				v-model="formData.price"
				fontSize="28rpx"
				inputAlign="right"
			></u--input>
		</view>
		
		<view class="form-item">
			<text class="form-label">备注</text>
			<u--textarea
				class="form-input"
				placeholder="请输入备注信息"
				placeholderStyle="color: #c0c4cc;"
				border="none"
				v-model="formData.remark"
				fontSize="28rpx"
				autoHeight
			></u--textarea>
		</view>
		
		<!-- 备注下方的空白区域 -->
		<view class="remark-placeholder"></view>
		
		<!-- 底部操作按钮 -->
		<view class="footer-actions">
			<view class="btn-save" hover-class="btn-save-hover" @click="saveParts">保存</view>
		</view>
		
		<!-- 加载中提示 -->
		<u-loading-page :loading="pageLoading" color="#1989fa"></u-loading-page>
	</view>
</template>

<script>
	import api from '@/utils/api.js'
	import {
		url
	} from '@/constant/domain'
	
	export default {
		data() {
			return {
				isEdit: false, // 是否是编辑模式
				partsId: null, // 配件ID
				fileList: [], // 上传的文件列表
				formData: {
					name: '', // 配件名称
					model: '', // 型号
					applicable: '', // 适用范围
					stock: '', // 库存
					price: '', // 价格
					remark: '', // 备注
					image: '' // 图片路径
				},
				pageLoading: false // 页面加载状态
			};
		},
		onLoad(options) {
			// 设置导航栏标题
			uni.setNavigationBarTitle({
				title: options.id ? '编辑配件' : '添加配件'
			});
			
			// 如果有ID参数，表示是编辑模式
			if (options.id) {
				this.isEdit = true;
				this.partsId = options.id;
				this.fetchPartsDetail();
			}
		},
		methods: {
			// 获取配件详情
			fetchPartsDetail() {
				this.pageLoading = true;
				api.getPartsDetail(this.partsId).then(res => {
					if (res) {
						// 填充表单数据
						this.formData = {
							...this.formData,
							...res
						};
						
						// 如果有图片，添加到图片列表
						if (res.image) {
							this.fileList = [{ url: res.image }];
						}
					} else {
						uni.showToast({
							title: '配件不存在',
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				}).catch(err => {
					console.error('获取配件详情失败:', err);
					uni.showToast({
						title: '获取配件详情失败',
						icon: 'none'
					});
				}).finally(() => {
					this.pageLoading = false;
				});
			},
			
			// 图片上传相关
			async afterRead(event) {
				const file = event.file[0];
				// 显示上传中的临时状态
				uni.showLoading({ title: '上传中...' });
				
				// 创建上传任务
				const uploadTask = uni.uploadFile({
					url: `${url}/common/upload`, // 上传文件服务器地址
					filePath: file.url,
					name: 'file', // 服务器接收的文件参数名
					header: {
						'Authorization': `Bearer ${this.$user.getToken()}` // 添加认证信息
					},
					success: (uploadRes) => {
						// 处理返回结果
						try {
							const result = JSON.parse(uploadRes.data);
							if (result.code === 200) {
							// 上传成功，更新文件列表和表单数据
							this.fileList = [{ url: `${url}${result.fileName}` }];
								this.formData.goodsImage = `${url}${result.fileName}`;
							} else {
								uni.showToast({
									title: result.msg || '上传失败',
									icon: 'none'
								});
							}
						} catch (e) {
							console.error('解析上传响应失败:', e);
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('上传失败:', err);
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
				
				// 监听上传进度
				uploadTask.onProgressUpdate((res) => {
					console.log('上传进度:', res.progress);
					// 可以在这里实现进度条
				});
			},
			
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				this.formData.image = '';
			},

			// 保存逻辑
			validateForm() {
				if (!this.formData.name) {
					uni.showToast({ title: '请输入配件名称', icon: 'none' });
					return false;
				}
				return true;
			},
			
			// 保存配件
			saveParts() {
				if (!this.validateForm()) return;
				
				
				uni.showLoading({ 
					title: '保存中...',
					mask: true // 添加遮罩防止重复点击
				});
				
				// 处理数值类型字段
				if (this.formData.stock) {
					this.formData.stock = Number(this.formData.stock);
				}
				if (this.formData.price) {
					this.formData.price = Number(this.formData.price);
				}
				
				// 根据是否是编辑模式调用不同的API
				const apiRequest = this.isEdit 
					? api.updateParts(this.formData)
					: api.addParts({...this.formData,category:1,state:1});
				
				apiRequest.then(res => {
					uni.hideLoading();
					uni.showToast({ 
						title: this.isEdit ? '更新成功' : '添加成功', 
						icon: 'success',
						duration: 1500
					});
					
					// 延迟返回，让用户看到成功提示
					setTimeout(() => {
						// 返回上一页
						uni.navigateBack({ delta: 1 });
					}, 800);
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: err || (this.isEdit ? '更新失败' : '添加失败'),
						icon: 'none',
						duration: 2000
					});
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
page {
    background-color: #f5f7fa;
}

.edit-parts-container {
    min-height: 100vh;
    background-color: #f5f7fa;
    padding-top: 40rpx; /* 增加顶部padding防止内容被状态栏遮挡 */
    padding-bottom: 120rpx;
    position: relative; /* 添加相对定位 */
}

// 图片上传
.upload-section {
    margin: 0 30rpx;
    margin-bottom: 20rpx;
    
    .upload-placeholder {
        width: 120rpx;
        height: 120rpx;
        background-color: #cad6e8;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border-radius: 0;
        
        text {
            font-size: 22rpx;
            color: #fff;
            margin-top: 4rpx;
        }
        
        &-hover {
            background-color: #a8b8d1;
            transform: scale(0.97);
        }
    }
}

// 表单项样式
.form-item {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    min-height: 80rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #f0f0f0;
    
    .form-label {
        color: #333;
        font-size: 28rpx;
        flex: 1;
        
        &.required {
            position: relative;
            &::before {
                content: "*";
                color: red;
                position: absolute;
                left: -14rpx;
            }
        }
    }
    
    .form-input {
        font-size: 28rpx;
        color: #999;
        flex: 1.5;
    }
}

// 备注下方的空白区域
.remark-placeholder {
    height: 260rpx;
    background-color: #f5f7fa;
}

// 底部按钮
.footer-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    height: 100rpx;
    
    .btn-save {
        flex: 1;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #1989fa;
        color: #fff;
        font-size: 30rpx;
        
        &-hover {
            background-color: #0c76d8;
            opacity: 0.9;
        }
    }
}
</style>